package logic

import (
	"context"
	"fmt"
	"math/rand"
	"month/model/redis"
	"month/pkg"
	"strconv"
	"time"

	"month/userrpc/internal/svc"
	"month/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *userrpc.SendSmsRequest) (*userrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	NumLoc := "sendSmsNum" + in.Source + in.Tel
	get := redis.Rdb.Get(NumLoc)

	if get.Val() != "" {
		return nil, fmt.Errorf("您已经发送过短信，请稍后再试")
	}

	i := rand.Intn(9000) + 1000
	resp, err := pkg.SendSms(in.Tel, strconv.Itoa(i))
	if err != nil {
		return nil, fmt.Errorf("短信发送失败")
	}
	if *resp.Body.Code != "OK" {
		return nil, fmt.Errorf(*resp.Body.Message)
	}

	redis.Rdb.Set(NumLoc, "1", time.Minute*1)
	redis.Rdb.Set("sendSms"+in.Source+in.Tel, i, time.Minute*5)

	return &userrpc.SendSmsResponse{}, nil
}
